/**
 * Thinking Step Card
 * 
 * 单个思维步骤的卡片展示组件
 */

import * as React from 'react';
import { 
  Brain, 
  Wrench, 
  Database, 
  Search, 
  Target, 
  CheckCircle, 
  RefreshCw,
  type LucideIcon
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import type { ThinkingStep, ThinkingStepType } from '@/types/thinking';
import { cn } from '@/lib/utils';

/**
 * 步骤类型配置
 */
const STEP_TYPE_CONFIG: Record<ThinkingStepType, {
  icon: LucideIcon;
  label: string;
  color: string;
  bgColor: string;
  borderColor: string;
}> = {
  reasoning: {
    icon: Brain,
    label: '推理',
    color: 'text-blue-600',
    bgColor: 'bg-blue-50',
    borderColor: 'border-blue-200',
  },
  tool_use: {
    icon: Wrench,
    label: '工具',
    color: 'text-green-600',
    bgColor: 'bg-green-50',
    borderColor: 'border-green-200',
  },
  retrieval: {
    icon: Database,
    label: '检索',
    color: 'text-purple-600',
    bgColor: 'bg-purple-50',
    borderColor: 'border-purple-200',
  },
  analysis: {
    icon: Search,
    label: '分析',
    color: 'text-orange-600',
    bgColor: 'bg-orange-50',
    borderColor: 'border-orange-200',
  },
  planning: {
    icon: Target,
    label: '计划',
    color: 'text-indigo-600',
    bgColor: 'bg-indigo-50',
    borderColor: 'border-indigo-200',
  },
  conclusion: {
    icon: CheckCircle,
    label: '结论',
    color: 'text-emerald-600',
    bgColor: 'bg-emerald-50',
    borderColor: 'border-emerald-200',
  },
  reflection: {
    icon: RefreshCw,
    label: '反思',
    color: 'text-pink-600',
    bgColor: 'bg-pink-50',
    borderColor: 'border-pink-200',
  },
};

export interface ThinkingStepCardProps {
  /** 思维步骤数据 */
  step: ThinkingStep;
  /** 步骤索引 */
  index: number;
  /** 是否展开 */
  expanded?: boolean;
  /** 展开/折叠回调 */
  onToggle?: () => void;
  /** 是否显示持续时间 */
  showDuration?: boolean;
  /** 是否显示置信度 */
  showConfidence?: boolean;
  /** 类名 */
  className?: string;
}

/**
 * 思维步骤卡片组件
 */
export function ThinkingStepCard({
  step,
  index,
  expanded = false,
  onToggle,
  showDuration = true,
  showConfidence = false,
  className,
}: ThinkingStepCardProps) {
  const config = STEP_TYPE_CONFIG[step.type];
  const Icon = config.icon;

  // 格式化持续时间
  const formatDuration = (ms?: number) => {
    if (!ms) return null;
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(1)}s`;
  };

  // 关键词高亮
  const highlightKeywords = (text: string) => {
    const keywords = ['问题分析', '解决方案', '实施步骤', '风险评估', '总结', '建议', '注意', '重要'];
    let highlightedText = text;
    
    keywords.forEach(keyword => {
      const regex = new RegExp(`(${keyword})`, 'gi');
      highlightedText = highlightedText.replace(
        regex, 
        '<strong class="text-primary font-semibold">$1</strong>'
      );
    });
    
    return highlightedText;
  };

  // 格式化内容（分段、列表）
  const formatContent = (text: string) => {
    // 识别并格式化数字列表
    const lines = text.split('\n');
    const formattedLines = lines.map(line => {
      // 数字列表: 1. 2. 3.
      if (/^\d+\.\s+/.test(line)) {
        return `<div class="ml-2 my-1">${line}</div>`;
      }
      // 项目符号: - * •
      if (/^[-*•]\s+/.test(line)) {
        return `<div class="ml-2 my-1">${line}</div>`;
      }
      // 空行作为段落分隔
      if (line.trim() === '') {
        return '<div class="h-2"></div>';
      }
      return line;
    });
    
    return formattedLines.join('\n');
  };

  // 内容是否应该截断（缩短到 100 字符）
  const shouldTruncate = step.content.length > 100;
  const displayContent = expanded || !shouldTruncate 
    ? formatContent(highlightKeywords(step.content))
    : formatContent(highlightKeywords(step.content.slice(0, 100))) + '...';

  return (
    <Card
      className={cn(
        'thinking-step-card',
        'transition-all duration-300 ease-in-out',
        'hover:shadow-md hover:-translate-y-0.5',
        'border-l-4',
        config.borderColor,
        className
      )}
    >
      <div className="p-4">
        {/* 头部：图标、标题、徽章 */}
        <div className="flex items-start gap-3 mb-3">
          {/* 图标 */}
          <div className={cn(
            'flex-shrink-0 w-10 h-10 rounded-lg flex items-center justify-center',
            config.bgColor
          )}>
            <Icon className={cn('w-5 h-5', config.color)} />
          </div>

          {/* 标题和元数据 */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <h4 className="font-semibold text-sm">
                {step.title}
              </h4>
              <Badge variant="outline" className="text-xs">
                {config.label}
              </Badge>
              {step.tool && (
                <Badge variant="secondary" className="text-xs">
                  {step.tool.name}
                </Badge>
              )}
            </div>

            {/* 元数据行 */}
            <div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
              <span>步骤 {index + 1}</span>
              {showDuration && step.duration && (
                <span>• {formatDuration(step.duration)}</span>
              )}
              {showConfidence && step.confidence !== undefined && (
                <span>• 置信度 {(step.confidence * 100).toFixed(0)}%</span>
              )}
            </div>
          </div>
        </div>

        {/* 内容 */}
        <div 
          className="text-sm text-foreground/90 leading-relaxed whitespace-pre-wrap"
          dangerouslySetInnerHTML={{ __html: displayContent }}
        />

        {/* 展开/折叠按钮 */}
        {shouldTruncate && onToggle && (
          <button
            onClick={onToggle}
            className="mt-3 text-xs text-primary hover:underline focus:outline-none font-medium"
          >
            {expanded ? '⬆ 收起' : '⬇ 查看更多'}
          </button>
        )}

        {/* 工具调用详情 */}
        {step.tool && expanded && (step.tool.input || step.tool.output) && (
          <div className="mt-3 pt-3 border-t space-y-2">
            {step.tool.input && (
              <div>
                <div className="text-xs font-medium text-muted-foreground mb-1">
                  输入:
                </div>
                <pre className="text-xs bg-muted p-2 rounded overflow-x-auto">
                  {JSON.stringify(step.tool.input, null, 2)}
                </pre>
              </div>
            )}
            {step.tool.output && (
              <div>
                <div className="text-xs font-medium text-muted-foreground mb-1">
                  输出:
                </div>
                <pre className="text-xs bg-muted p-2 rounded overflow-x-auto">
                  {JSON.stringify(step.tool.output, null, 2)}
                </pre>
              </div>
            )}
          </div>
        )}

        {/* 子步骤 */}
        {step.children && step.children.length > 0 && expanded && (
          <div className="mt-3 pl-4 border-l-2 border-muted space-y-2">
            {step.children.map((child, i) => (
              <ThinkingStepCard
                key={child.id}
                step={child}
                index={i}
                expanded={false}
                showDuration={showDuration}
                showConfidence={showConfidence}
                className="bg-muted/30"
              />
            ))}
          </div>
        )}
      </div>
    </Card>
  );
}

